﻿using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Windows.Forms;

namespace mki.Backup.Service
{
	/// <summary>
	/// Represents the ProjectInstaller class
	/// </summary>
	[RunInstaller(true)]
	public partial class ProjectInstaller : Installer
	{
		#region Constructors (1)

		/// <summary>
		/// Initializes a new instance of the <see cref="ProjectInstaller"/> class.
		/// </summary>
		public ProjectInstaller()
		{
			InitializeComponent();

			this.serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
			this.serviceProcessInstaller.Username = null;
			this.serviceProcessInstaller.Password = null;

			this.BeforeUninstall += this.projectInstallerBeforeInstall;
			this.Committed += this.projectInstallerCommitted;
		}

		#endregion Constructors

		#region Methods (4)

		// Private Methods (4) 

		/// <summary>
		/// Projects the installer before install.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.Configuration.Install.InstallEventArgs"/> instance containing the event data.</param>
		private void projectInstallerBeforeInstall(object sender, InstallEventArgs e)
		{
			this.stopService();
		}

		/// <summary>
		/// Projects the installer committed.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.Configuration.Install.InstallEventArgs"/> instance containing the event data.</param>
		private void projectInstallerCommitted(object sender, InstallEventArgs e)
		{
			this.startService();
		}

		/// <summary>
		/// Starts the service.
		/// </summary>
		private void startService()
		{
			try
			{
				var serviceController = new ServiceController(this.serviceInstaller.DisplayName);

				if (serviceController.Status == ServiceControllerStatus.Stopped)
				{
					serviceController.Start();
					serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(String.Format("Error while starting service: {0}\n{1}", ex.Message, ex.StackTrace));
			}
		}

		/// <summary>
		/// Stops the service.
		/// </summary>
		private void stopService()
		{
			try
			{
				var serviceController = new ServiceController(this.serviceInstaller.DisplayName);
				if (serviceController.Status == ServiceControllerStatus.Running)
				{
					serviceController.Stop();
					serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(String.Format("Error while stopping service: {0}\n{1}", ex.Message, ex.StackTrace));
			}
		}

		#endregion Methods
	}
}